package org.xqh.test.yzs.trlog;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.xqh.test.yzs.nlu.FindNluLogTest;
import org.xqh.utils.DateUtil;
import org.xqh.utils.file.ReadTxtFileUtils;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.StringUtils;

import java.io.File;
import java.util.*;
import java.util.Map.Entry;

/**
 * @ClassName TRLogAnalysis
 * @Description 分析TR 日志 计算一次语音交互 耗时情况
 * @Author xuqianghui
 * @Date 2020/3/5 15:41
 * @Version 1.0
 */
public class TRLogAnalysis {

    private static String endService = "serviceReqCmd=normalEndService";

    private static String appKey = "nmugoqugf3ikbhkhbaixhefxdinqcmgyhobsvjiv";

    private static String startService = "serviceReqCmd=requestService";

    private static String cur_path = "E:\\secureCRT_file\\download\\";

    private static String tr_url = "http://route.igaicloud.cn:8088/";

    private static String session = "JJSESSIONID=9F9F8C6B610987AF9D86A7A7B52C584C";//当前TR 登录session

    private static String audio_out = "cd-out\\";

    private static List<Date> date_limit = Arrays.asList(
            DateUtil.parseDate("2020-03-19 14:30:00", DateUtil.DATE_PATTERN_COMPLEX),
            DateUtil.parseDate("2020-03-19 15:30:00", DateUtil.DATE_PATTERN_COMPLEX)
    );

    private static Map<String, ParseData> dataMap = Maps.newHashMap();

    public static void downloadAudioByFile(){
        List<String> sessionIds = ReadTxtFileUtils.readTxt(new File(cur_path + "dddd.txt"));
        for(String reqId:sessionIds){
            downloadAudio(reqId);
        }
    }

    public static void main(String[] args) {
          List<String> list = ReadTxtFileUtils.readTxt(new File("C:\\Users\\YZS\\Desktop\\IDS.txt"));
          List<String> ids = Lists.newArrayList();
          for(String s:list){
              JSONObject json = JSON.parseObject(s);
              JSONArray array =  json.getJSONArray("data");
              for(Object obj:array){
                  JSONObject o = (JSONObject) obj;
                  String spaceId = o.getString("id");
                  if(!ids.contains(spaceId)){
                      ids.add(spaceId);
                  }
              }
          }
        System.out.println(ids.size());
        System.out.println(JSON.toJSONString(ids));

//        downloadAudioByFile();
    }


    public static void main22(String[] args) {

//        List<String> list = ReadTxtFileUtils.readTxt(new File("LTE3Nzg0MjcyMTUwMEVDRTE1NEYwMUVGQw-tr.log"));
        List<String> list = FindNluLogTest.getFileList(cur_path + "LTE3Nzg0MjcyMTUwMEVDRTE1NEYwMjdBNg-tr.log");
        for (String str : list) {
            String requestId = FindNluLogTest.getRequestId(str);
            Date date = FindNluLogTest.parseDateFromLog(str);
            if (Objects.isNull(date) || date.compareTo(date_limit.get(0)) < 0
                    || date.compareTo(date_limit.get(1)) > 0) {
                continue;
            }
            if (!dataMap.containsKey(requestId)) {
                dataMap.put(requestId, ParseData.builder()
                        .list(Lists.newArrayList())
                        .build());
            }
            MatchModel m = MatchModel.builder()
                    .requestId(requestId)
                    .content(str)
                    .date(FindNluLogTest.parseDateFromLog(str))
                    .build();
            if (str.contains(startService)) {
                if(str.contains(appKey)){
                   dataMap.get(requestId).setAppKey(appKey);
                }
                m.setStart(true);
            }
            if (str.contains(endService)) {
                m.setEnd(true);
            }
            dataMap.get(requestId).getList().add(m);
        }
        Map<String, ParseData> usefulMap = Maps.newHashMap();
        for(Entry<String, ParseData> entry:dataMap.entrySet()){
            if(StringUtils.hasText(entry.getValue().getAppKey())){
                usefulMap.put(entry.getKey(), entry.getValue());
            }
        }
        Set<String> hasNoEnd = Sets.newHashSet();//没有正常结束的请求
        for (Entry<String, ParseData> entry : usefulMap.entrySet()) {
            Optional<MatchModel> start = entry.getValue().getList().stream().filter(d -> d.isStart()).findAny();
            Optional<MatchModel> end = entry.getValue().getList().stream().filter(d -> d.isEnd()).findAny();
            if (start.isPresent() && end.isPresent()) {
                System.out.println("sessionId: " + entry.getKey() + "  耗时: " + (end.get().getDate().getTime() -
                        start.get().getDate().getTime()) / 1000 + "秒");
                downloadAudio(entry.getKey());
            } else {
                hasNoEnd.add(entry.getKey());
            }
        }
        System.out.println("=======================");
        System.out.println(JSON.toJSONString(hasNoEnd));
        System.out.println("总记录数: " + usefulMap.size() + " 异常记录数: " + hasNoEnd.size());
//        System.out.println(JSON.toJSONString(dataMap.get("0ebf4bbb8c4d650c4bd695f8fb7d07e3")));
        List<Object> list1 = Lists.newArrayList();
        List<ParseData> listResult = JSONArray.parseArray(JSON.toJSONString(list1), ParseData.class);
    }

    public static void downloadAudio(String requestId){
        String downloadPath = cur_path.concat(audio_out);
        DownloadTRLogAudio.downloadAudio(tr_url, requestId, session, downloadPath, ".wav");
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class ParseData{
        private List<MatchModel> list;
        private String appKey;
    }

    @Data
    @Builder
    @AllArgsConstructor
    @NoArgsConstructor
    public static class MatchModel {

        private String requestId;

        private boolean isStart;

        private boolean isEnd;

        private Date date;

        private String content;

        private long cost;//耗时

    }
}
